//
//  CalendarExampleViewController.m
//  CalendarExample
//

#import "CalendarExampleViewController.h"

@implementation CalendarExampleViewController

- (void)createBirthdayEvent
{
    EKEventStore *eventStore = [[EKEventStore alloc] init];
    
    // 생일에 해당하는 날짜 생성
    NSDateComponents *comp = [[NSDateComponents alloc] init];
	[comp setDay:21];
	[comp setMonth:2];
	[comp setYear:2011];
	NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDate *eventDate = [cal dateFromComponents:comp];
    
    // 이벤트 반복 규칙 준비
	EKRecurrenceRule *recurrence = [[EKRecurrenceRule alloc]
									initRecurrenceWithFrequency:EKRecurrenceFrequencyYearly
									interval:1
									end:[EKRecurrenceEnd
										 recurrenceEndWithEndDate:[NSDate distantFuture]]];
    
    // 생일 하루 전에 알람 설정
    double alarmAmountInSeconds = 60.0 * 60.0 * 24.0;
	EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:(-1.0 * alarmAmountInSeconds)];
    
    // 이벤트 생성
    EKEvent *myEvent = [EKEvent eventWithEventStore:eventStore];
	myEvent.calendar = eventStore.defaultCalendarForNewEvents;
	myEvent.title = @"My Birthday";
	myEvent.startDate = eventDate;
	myEvent.endDate = eventDate;
	myEvent.allDay = TRUE;
	myEvent.recurrenceRule = recurrence;
	myEvent.alarms = [NSArray arrayWithObject:alarm];
	myEvent.notes = @"Remember to buy a present!";
    
    // 캘린더에 이벤트 추가
    NSError *err = nil;
	BOOL result = [eventStore saveEvent:myEvent span:EKSpanFutureEvents error:&err];
    
    // 결과 출력
	if (!result) {
		NSLog(@"error saving event: %@",err);
	} else {
		NSLog(@"event (%@) saved",myEvent.eventIdentifier);
	}

    [recurrence release];
    [cal release];
    [comp release];
    [eventStore release];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	[self createBirthdayEvent];
}

- (void)dealloc {
    [super dealloc];
}

@end
